﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Seven.Site.Log
{
    public class FileLoger
    {
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="content">日志内容</param>
        /// <param name="path">日志文件的相对路径，若不提供，则采用日志配置中的路径</param>
        public static void WriteLog(string content, string path = "")
        {
            string dir = AppDomain.CurrentDomain.BaseDirectory;
            string root = "\\" + Seven.Service.SiteCore.DefaultProjectRootName + "\\";
            int index = dir.IndexOf(root);
            dir = dir.Substring(0, index + root.Length);
            dir += Seven.Service.SiteCore.DefaultProjectAssemblyName + "\\";

            string realPath = path;
            if (string.IsNullOrWhiteSpace(realPath)) { realPath = dir + LogerConfig.LogFilePath; }
            else { realPath = dir + realPath; }
            try
            {
                if (!System.IO.Directory.Exists(realPath))
                {
                    System.IO.Directory.CreateDirectory(realPath);
                }
                realPath = realPath + LogerConfig.LogFileName;
                
                System.IO.FileInfo fileInfo;
                if (System.IO.File.Exists(realPath))
                {
                    fileInfo = new System.IO.FileInfo(realPath);
                    if (fileInfo.Length > 8024000)
                    {
                        if (!System.IO.Directory.Exists(LogerConfig.LogFileBakPath))
                        { System.IO.Directory.CreateDirectory(LogerConfig.LogFileBakPath); }

                        System.IO.File.Move(realPath, LogerConfig.LogFileBakPath + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ".bak." + LogerConfig.LogFileName);
                    }
                }
                System.IO.File.AppendAllText(realPath, DateTime.Now.ToString() + "：" + content + Environment.NewLine);
            }
            catch { }
        }

    }
}
